import { Tools, Modal, Toast } from 'weaver-mobile';
import base from './base';
import * as taskUtil from './taskUtil';
import { buildUrlStr } from './forwardPage';

//getLabel兼容
export const getLabel = (labelid, defvalue) => {
    return Tools.getLabel(labelid, defvalue);
}

//弹确认框
export const showConfirm = (obj = {}, hasCancel = true) => {
    const def = {
        title: getLabel(131329, '信息确认'),
        content: "",
        cancelText: getLabel(201, '取消'),
        okText: getLabel(826, '确定'),
        cancelEvent: () => { },
        okEvent: () => { }
    };
    const params = { ...def, ...obj };
    let btns = [];
    if (hasCancel){
        btns.push({
            text: params.cancelText, 
            onPress: ()=>{
                typeof params.cancelEvent === 'function' && params.cancelEvent();
                taskUtil.controllBottomBtnDisable(false);
            }, 
            style: 'default' 
        });
    }
    btns.push({
        text: params.okText, 
        onPress: ()=>{
            typeof params.okEvent === 'function' && params.okEvent();
            taskUtil.controllBottomBtnDisable(false);
        }
    });
    let dialog = Modal.alert(params.title, params.content, btns); 
    taskUtil.controllBottomBtnDisable(true);
    return dialog;
}

//打开相关流程
export const showFormReq = (requestid, params={}, baseRoute) =>{
    const urlParams = {...generateAuthParams(false), ...params, ...{requestid}};
    const url = `/spa/workflow/forwardMobileForm.html?${buildUrlStr(urlParams)}`;
    showHoverWindow(url, baseRoute);
}

//打开相关文档
export const showFormDoc = (docid, params={}, baseRoute) =>{
    const urlParams = {...generateAuthParams(true), ...params};
    const docViewUrl = base.wfGlobalStore.commonParam.docViewUrl || "";
    const url = `${docViewUrl.replace("${docid}", docid)}?${buildUrlStr(urlParams)}`;
    showHoverWindow(url, baseRoute,true);
}

//打开附件(展示的文档模块的附件预览界面)
export const showFormAttach = (fileObj, params = {}, baseRoute, detailtype) =>{
    const { commonParam ,variableMap} = base.wfGlobalStore;
    const { mobileSupportViewFileType = [] } = commonParam;
    if(mobileSupportViewFileType.includes(fileObj.fileExtendName)){
        if(judgeIsImage(fileObj, detailtype) && !fileObj.hasOwnProperty("isPreViewImg")){
            if(fileObj.loadlink){
                window.preViewImg(fileObj.loadlink);
            }else{
                window.WfForm.downLoadFile(fileObj.imagefileid, baseRoute);
            }
        }else{
            let imagefileId = fileObj.imagefileid;
            if(variableMap.has(`imagefiledId_${imagefileId}`)) imagefileId = variableMap.get(`imagefiledId_${imagefileId}`);
            const urlParams = {...generateAuthParams(true), ...params};
            const fileViewUrl = base.wfGlobalStore.commonParam.fileViewUrl;
            const url = `${fileViewUrl.replace("${fileid}", imagefileId)}?${buildUrlStr(urlParams)}`;
            showHoverWindow(url, baseRoute,true);
        }
    }else{
        window.WfForm.downLoadFile(fileObj.imagefileid, baseRoute);
    }
}

 //判断是否是图片元素点击
 export const judgeIsImage=(file,detailtype)=>{
    const filetype = file.fileExtendName || "";
    return detailtype === 2 || (filetype !== "" && /(jpg|jpeg|png|gif|bmp)/.test(filetype))
}

//打开别的模块的页面(带签名串和其他参数)
export const showModulePage = (url, params = {}, baseRoute) => {
    const urlParams = { ...generateAuthParams(false), ...params };
    url = `${url}${url.indexOf("?") === -1 ? "?" : "&"}${buildUrlStr(urlParams)}`;
    showHoverWindow(url, baseRoute);
}

const generateAuthParams = (needRequest=true) =>{
    const { commonParam } = base.wfGlobalStore;
    const { requestid,authStr,authSignatureStr,f_weaver_belongto_userid,f_weaver_belongto_usertype } = commonParam;
    const auth = {authStr,authSignatureStr,f_weaver_belongto_userid,f_weaver_belongto_usertype,isrequest:"1",__random:new Date().getTime()};
    if(needRequest)
        auth.requestid = requestid;
    return auth;
}
//判断是否是EM终端,支持弹webview的SDK
export const judgeSupportOpenSDK = () =>{
    const isEmobile = Tools.mobileDetect().isEmobile();
    if(isEmobile && window.em)
        return window.em.checkJsApi("openLink") && window.em.checkJsApi("closeWindow");
    return false;
}
//弹层打开指定链接(支持所有页面，默认为表单中打开)
export const showHoverWindow = (url, baseRoute="/req",isWindowOpen) =>{
    if(judgeSupportOpenSDK()){
        window.em.openLink({
            openType: 2,
            title: "",
            url: url
        });
    }else if(isWindowOpen==true){
        window.open(url)
    }else{
        const currentIsHover = window.top.location.href.indexOf("/hoverWindow") > -1;
        console.log("currentIsHover",currentIsHover,"url",url);
        if(currentIsHover){     //当前本身在弹出层的修改iframe地址实现
            const iframeDom = window.top.jQuery("#__hoverIframe");
            iframeDom.attr("src", url);
        }else{
            window.historyRoute.push({
                pathname: `${baseRoute}/hoverWindow`,
                iframeUrl: url
            });
        }
    }
}

window.showFormReq = showFormReq;
window.showFormDoc = showFormDoc;
window.showModulePage = showModulePage;
window.showFormAttach = showFormAttach;
window.showHoverWindow = showHoverWindow;